package com.jishuo.base.interceptor;

import com.google.gson.Gson;
import com.jishuo.base.annotation.UserAuthority;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.vo.UserVO;
import com.jishuo.base.config.AppConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 核心拦截器，权限判断
 */
@Component
public class CoreInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 是否 ajax 请求
        boolean ajax = request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest");
        String ctxPath = request.getContextPath();
        // 从session获取user
        UserVO user = (UserVO)request.getSession().getAttribute(AppConfig.LOGIN_USER_SESSION_KEY);
        if (user == null) {
            if (ajax) {
                BaseResult ret = new BaseResult(ErrorCodeEnum.NO_LOGIN);
                returnJson(response, new Gson().toJson(ret));
            } else {
                response.sendRedirect(ctxPath + "/index/login");	//未登录，跳转到登录页
            }
            return false;
        }

        if (handler instanceof HandlerMethod) {
            // 获得权限注释，没有注释认为无权限
            UserAuthority annotation = ((HandlerMethod) handler).getMethod().getAnnotation(UserAuthority.class);
            if (annotation == null) {
                annotation = ((HandlerMethod) handler).getBeanType().getAnnotation(UserAuthority.class);
            }

            if (this.chkAuth(annotation, user)) return true;

            if (ajax) {
                BaseResult ret = new BaseResult(ErrorCodeEnum.NO_AUTH);
                returnJson(response, new Gson().toJson(ret));
            } else {
                response.sendRedirect(ctxPath + "/assets/noauth.html");	//权限不足
            }
            return false;
        }

        return false;
    }

    /**
     * 检查用户是否有权限
     * @param annotation 注释权限
     * @param user 登录用户
     * @return
     */
    private boolean chkAuth(UserAuthority annotation, UserVO user) {
        return true;
        /*
        if (annotation == null) return false;
        // 检查角色
        if (annotation.role().length > 0) {
            boolean auth = false;
            String ur = "," + user.getRole() + ",";
            for (RoleType rt : annotation.role()) {
                if (ur.contains("," + rt.getCode() + ",")) {
                    auth = true;
                    break;
                }
            }
            if (!auth) return false;
        }
        // 检查url
        if (annotation.menu().length > 0) {
            for (String mu : annotation.menu()) {
                for (String url : user.getMenuUrls()) {
                    if (url.equals(mu)) return true;
                    // 通配符配置时验证
//                    AntPathMatcher antPathMatcher = new AntPathMatcher();
//                    if (antPathMatcher.match(mu, url)) return true;
                }
            }
            return false;
        } else {
            return true;
        }

         */
    }

    /**
     * 返回json
     * @param response
     * @param json
     * @throws Exception
     */
    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
